/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wli.web.java.db;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author wli
 */
public class VocabularyHelper {

    Session session = null;

    public VocabularyHelper() {
        //System.out.println("++++++++++++++++++++VocabularyHelper Initial ++++++++++++++aaaaaaaaaaaaaaaaaaaaa+++++++++++");
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    public List<Vocabulary> getVocabularyList() {
        //System.out.println("++++++++++++++++++++VocabularyHelper Initial ++++++++++++++aabbbbbbbbbbbbbbbbbbbbbbbbb+++++++++++");
        List<Vocabulary> vocabularyList = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Vocabulary");
            vocabularyList = (List<Vocabulary>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vocabularyList;
    }

    public Vocabulary getVocabularyByID(String word) {

        Vocabulary vc = null;

        //System.out.println("++++++++++++++++++++VocabularyHelper Initial +++++++++++++cccccccccccccccccccccc++++++++++++");
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = null;
            if (word == null) {
                //System.out.println("++++++++++++++++++++VocabularyHelper Initial ++++++++++ddddddddddddddddd+++++++++++++++");
                q = session.createQuery("from Vocabulary");
            } else {
                q = session.createQuery("from Vocabulary as vc where vc.word = '" + word + "'");
            }
            vc = (Vocabulary) q.list().get(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return vc;
    }

    public void updateVocabulary(String word, String definition) {

        Vocabulary vc = new Vocabulary();
        vc.setWord(word);
        vc.setDefinition(definition);

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            session = HibernateUtil.getSessionFactory().openSession();
            transaction = session.beginTransaction();
            session.update(vc);
            transaction.commit();
            //session.close();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}
